package com.itheima.web.servlet;

import com.itheima.domain.User;
import com.itheima.service.Impl.UserServiceImpl;
import com.itheima.service.UserService;
import org.apache.commons.beanutils.BeanUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

// 增删改 使用重定向  查询用请求转发
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置请求编码
        request.setCharacterEncoding("utf-8");
        String methodName = request.getParameter("method");
        if("findAll".equals(methodName)){
            findAll(request,response);
        }else if("add".equals(methodName)){
            add(request,response);
        }


    }

    private void add(HttpServletRequest request, HttpServletResponse response) {



        try {

            //2. 获取所有请求参数的map集合
            Map<String, String[]> map = request.getParameterMap();
            //3. 封装数据到user对象
            User user = new User();
            BeanUtils.populate(user,map);
            //4. 指挥service 进行添加操作
            UserService service = new UserServiceImpl();
            service.add(user);
            //5. 重定向到查看页面
            response.sendRedirect(request.getContextPath()+"/userServlet?method=findAll");
        }  catch (Exception e) {
            e.printStackTrace();
        }


    }

    /*public void add(HttpServletRequest request, HttpServletResponse response) throws IOException, InvocationTargetException, IllegalAccessException {


    }*/

    protected void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserService service = new UserServiceImpl();
        //指挥service 进行查找

        List<User> userList = service.findAll();
        System.out.println(userList);
        //存入request域中
        request.setAttribute("userList",userList);

        //请求转发到list.jsp
        request.getRequestDispatcher("/list.jsp").forward(request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request, response);
    }



}
